﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using IRC.IRepairClouds.DataLayer;

namespace IRC.IRepairClouds.WebClient
{
    public class PagesAuthorized
    {
        public Dictionary<PagesAuthorization.Pages, Tuple<bool, AuthRequirements>> Pages { get; set; }

        public Dictionary<UrlParser, bool> Urls { get; set; }
        public Dictionary<UrlParser, bool> AbsoluteUrls { get; set; }
        public Dictionary<string, bool> Keys { get; set; }

        public PagesAuthorized()
        {
            Pages = new Dictionary<PagesAuthorization.Pages, Tuple<bool, AuthRequirements>>();
            Urls = new Dictionary<UrlParser, bool>();
            AbsoluteUrls = new Dictionary<UrlParser, bool>();
            Keys = new Dictionary<string, bool>(StringComparer.InvariantCultureIgnoreCase);
        }

        private static bool IsUrlAllowedInternal(string url, Dictionary<UrlParser, bool> urls)
        {
            UrlParser bestMatch = null;
            bool allowed = false;
            int matchLevel = -1;

            UrlParser up = new UrlParser(url.ToLowerInvariant());
            foreach (var i in urls)
            {
                if (i.Key.Url == up.Url)
                {
                    int tm = 0;
                    foreach (var q in i.Key.Queries)
                    {
                        string val;
                        if (up.Queries.TryGetValue(q.Key, out val))
                        {
                            if (val == q.Value)
                                tm++;
                        }
                    }
                    if (tm > matchLevel && tm == i.Key.Queries.Count)
                    {
                        matchLevel = tm;
                        bestMatch = i.Key;
                        allowed = i.Value;
                    }
                }
            }
            if (bestMatch != null)
                return allowed;
            return false;
        }

        public bool IsUrlAllowed(string url)
        {
            return IsUrlAllowedInternal(url, Urls);
        }

        public bool IsAbsoluteUrlAllowed(string url)
        {
            return IsUrlAllowedInternal(url, AbsoluteUrls);
        }

        public bool IsKeyAllowed(string key)
        {
            bool allowed;
            if (Keys.TryGetValue(key, out allowed))
                return allowed;
            return false;
        }

        public bool IsPageAllowed(PagesAuthorization.Pages page)
        {
            Tuple<bool, AuthRequirements> allowed;
            if (Pages.TryGetValue(page, out allowed))
                return allowed.Item1;
            return false;
        }

        public AuthRequirements GetPageAuthRequirements(PagesAuthorization.Pages page)
        {
            return this.Pages.GetValueDef(page).Item2;
        }
    }
}